package cn.itsource.ymcc.service.impl;

import cn.itsource.ymcc.domain.Login;
import cn.itsource.ymcc.exception.GlobalException;
import cn.itsource.ymcc.mapper.LoginMapper;
import cn.itsource.ymcc.result.JsonResult;
import cn.itsource.ymcc.service.ILoginService;
import cn.itsource.ymcc.util.AssertUtil;
import cn.itsource.ymcc.util.jwt.JwtUtils;
import cn.itsource.ymcc.util.jwt.PayloadData;
import cn.itsource.ymcc.util.jwt.RsaUtils;
import cn.itsource.ymcc.vo.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 登录表 服务实现类
 * </p>
 *
 * @author zongchangjiang
 * @since 2023-07-23
 */
@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, Login> implements ILoginService {

    //登录
    @Override
    public JsonResult login(LoginVo loginVo) {

        //去数据库校验
        Login login = baseMapper.selectOne(new QueryWrapper<Login>()
                .eq("username", loginVo.getUsername())
                .eq("type",loginVo.getType()));
        //判断 根据用户名是否能查询到用户
        AssertUtil.isNotNull(login,"用户名或密码错误");//断言

        boolean matches = new BCryptPasswordEncoder().matches(loginVo.getPassword(), login.getPassword());
        AssertUtil.isTrue(matches,"用户名或密码错误");

        //生成token
        return JsonResult.success().setData(buildToken(login));
    }

    private Map<String,Object> buildToken(Login login){
        Map<String,Object> map =  new HashMap<>();
        try {
            //1.用户类型为0的时候（后台管理系统用户），连表查询当前登录用户拥有的权限和菜单  [今天先不做]
            //2.JWT工具类生成JWT字符串  私钥加密  公钥解密
            PrivateKey privateKey = RsaUtils
                    .getPrivateKey(FileCopyUtils
                            .copyToByteArray(this.getClass().getClassLoader().getResourceAsStream("hrm_auth_rsa")));
            //加密得到token
            PayloadData payloadData = new PayloadData();
            login.setPassword(null);    //置空密码，更安全
            payloadData.setLogin(login);
            String token = JwtUtils.generateTokenExpireInMinutes(payloadData, privateKey, 60*24);  //24小时过期
            map.put("token",token);
            map.put("currentUser",login);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

//    public static void main(String[] args) {
//        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//
//        String encode = bCryptPasswordEncoder.encode("123");
//        System.out.println(encode);
//        boolean matches = bCryptPasswordEncoder.matches("123", "$2a$10$WW2XcD/aswwMhgjbz8v3juv7YZuwOmGMmJX0AvMBRiFrEu2zJ33BO");
//        System.out.println(matches);
//    }

}
